import React from 'react';
import './person.css'

import { Card, Descriptions, Button, Modal, Form, Input, message } from 'antd';
import PubSub from "pubsub-js";
import axios from "axios";
import memoryUtils from "../../utils/memoryUtils";
import storageUtils from "../../utils/storageUtils";


const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 8 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 16 },
    },
};


export default class Person extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      u_id: '',
      username: '',
      password: '',
      phone: '',
      mail: '',
      visible:false,
      confirmLoading:false,
    }
  }

  componentDidMount(){
    let orderNumber = 5;
    PubSub.publish("sendOrderNumber5", orderNumber);

    this.setState({
      username: memoryUtils.user.username,
    })

    let data = { username: memoryUtils.user.username }
    let url = '/registrationapi/getinfo'
    axios.post(url, data, {headers: {'Content-Type': 'application/json'}}
      ).then(res=>{
        if(res.status === 200 && res.data.code === 0){
          this.setState({
            u_id: res.data.userinfo['id'],
            password: res.data.userinfo['password'],
            phone: res.data.userinfo['phone'],
            mail: res.data.userinfo['email']
          })
        } else {
          console.log(res)
          message.error('获取失败！')
        }
    })
  }

  showModal = () => {
    this.setState({
      visible:true
    });
  };

  handleOk = (values) => {
    this.setState({
      confirmLoading:true
    });
    let data = {
      id: this.state.u_id,
      username: values.username,
      old_password: values.old_password,
      new_password: values.new_password,
      phone: values.phone,
      email: values.email,
    }
    let url = '/registrationapi/editinfo'
    axios.post(url, data, {headers: {'Content-Type': 'application/json'}}
      ).then(res=>{
        if(res.status === 200 && res.data.code === 0){
          message.success('编辑成功！')
          memoryUtils.user = res.data.userinfo
          storageUtils.saveUser(res.data.userinfo)
          this.setState({
            username: res.data.userinfo['username'],
            password: res.data.userinfo['password'],
            phone: res.data.userinfo['phone'],
            mail: res.data.userinfo['email'],
            visible: false,
            confirmLoading: false,
          });
        } else {
          console.log(res)
          message.error('编辑失败：' + res.data.msg)
        }
    })
  };

  handleCancel = () => {
    this.setState({
      visible:false
    });
  };


  render() {
    return (
      <div className="person">
        <Descriptions title="个人信息" column={1} bordered>
          <Descriptions.Item label="用户名">{this.state.username}</Descriptions.Item>
          <Descriptions.Item label="密码">********</Descriptions.Item>
          <Descriptions.Item label="电话号码">{this.state.phone}</Descriptions.Item>
          <Descriptions.Item label="电子邮箱">{this.state.mail}</Descriptions.Item>
        </Descriptions>
        <div className="person-button">
          <Button type="primary" style={{ float:'right', width:450, height:40}} onClick={this.showModal} >编辑</Button>
          <Modal
            title="编辑个人信息"
            visible={this.state.visible}
            confirmLoading={this.state.confirmLoading}
            onCancel={this.handleCancel}
            footer={null}
          >
            <Form {...formItemLayout} scrollToFirstError onFinish={this.handleOk}>
              <Form.Item
                name="username"
                label="用户名"
                initialValue={this.state.username}
                rules={[{ required: true, message: '请输入您的用户名！', whitespace: true }]}
              >
                <Input />
              </Form.Item>

              <Form.Item
                name="old_password"
                label="原始密码"
                hasFeedback
              >
                <Input.Password />
              </Form.Item>

              <Form.Item
                name="new_password"
                label="新密码"
                hasFeedback
              >
                <Input.Password />
              </Form.Item>

              <Form.Item
                name="new_password_confirm"
                label="再次输入新密码"
                dependencies={['new_password']}
                hasFeedback
                rules={[
                  {
                    required: true,
                    message: '请再一次输入您的新密码！',
                  },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('new_password') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('您两次输入的密码不匹配！'));
                    },
                  }),
                ]}
              >
                <Input.Password />
              </Form.Item>

              <Form.Item
                name="phone"
                label="电话号码"
                initialValue={this.state.phone}
                rules={[{ required: true, message: '请输入您的电话号码！' }]}
              >
                <Input style={{width:'100%'}} />
              </Form.Item>

              <Form.Item
                name="email"
                label="电子邮箱"
                initialValue={this.state.mail}
                rules={[
                  {
                    type: 'email',
                    message: '输入的不是有效的电子邮箱！',
                  },
                  {
                    required: true,
                    message: '请输入您的电子邮箱！',
                  },
                ]}
              >
                <Input />
              </Form.Item>

              <Form.Item>
                <Button type="primary" htmlType="submit" className="person-form-save" >保存</Button>
                <Button className="person-form-cancel" onClick={this.handleCancel}>取消</Button>
              </Form.Item>
            </Form>
          </Modal>
        </div>
      </div>
    );
  }
}